import os
from common.enum import MyEnum, Runner
from common.base_act import BaseAct
import time


class SUSEAct(BaseAct):

    def add_repo(self):
        # clean repository before adding new repository
        self.clean_repo()
        official_repo = self.config.official_repo
        third_repo = self.config.third_repo
        cmd = 'sudo zypper --gpg-auto-import-keys addrepo --check --refresh --name "%s" %s "%s"'
        repos = []
        for k, v in official_repo.items():
            repos.append(cmd % (k, v, k))
        repos += third_repo
        self.execute_cmd(repos)

    def install_software(self):
        s = self.config.dev_soft
        if self.mode == MyEnum.laptop_mode.value:
            s += self.config.laptop
        for soft in s:
            os.system('sudo zypper --gpg-auto-import-keys in -y %s' % soft.strip())

    def clean_repo(self):
        repo_dir = '/etc/zypp/repos.d/'
        repos = os.listdir(repo_dir)
        for repo in repos:
            os.unlink(os.path.join(repo_dir, repo))

    def suse_bash(self):
        self.write_bash(self.env[MyEnum.user_home.value])

    def env_requirement(self):
        requirement = self.config.py_module
        requirement = self.parse_cmd(requirement)
        self.install_py_module(requirement)

    @staticmethod
    def restart_network():
        os.system('sudo systemctl restart NetworkManager')
        time.sleep(10)

    def all_runner(self):
        ar = Runner("add repository", self.add_repo)
        in_soft = Runner("install software", self.install_software)
        wb = Runner("write bash", self.suse_bash)
        ai = Runner("add pip index", self.add_pip_index)
        py_mod = Runner("install py module", self.env_requirement)
        _all = [ar, in_soft, wb, ai, py_mod]
        runners = {
            MyEnum.restore_auto.value: _all,
            MyEnum.restore_all.value: _all
        }
        return runners
